package com.ruibo.tax.service.impl;

import com.ruibo.tax.model.FHTQXX;
import com.ruibo.tax.model.base.PackageHead;
import com.ruibo.tax.model.log.TaxDataLog;
import com.ruibo.tax.model.log.TaxLog;
import com.ruibo.tax.model.xml2bean.FHTQXXXMLEncodeModel;
import com.ruibo.tax.mq.send.ReconciliationSendZIPMessage;
import com.ruibo.tax.repository.SWHBSWFHTQRepository;
import com.ruibo.tax.service.FHTQXXService;
import com.ruibo.tax.service.TaxDataLogService;
import com.ruibo.tax.service.TaxLogService;
import com.ruibo.tax.utils.XMLUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Zhang Jibing
 * @version 1.0
 * @date 2020/10/15 16:16
 * @company Jinan RuiBo Information Technology Co., Ltd
 * @address Jinan, China
 */
@Slf4j
@Service
public class FHTQXXServiceImpl implements FHTQXXService {

    @Autowired
    private SWHBSWFHTQRepository swhbswfhtqRepository;

    @Autowired
    private TaxLogService taxLogService;

    @Autowired
    private TaxDataLogService taxDataLogService;


    @Override
    @Transactional
    public void save(List<FHTQXX> roots) {
        swhbswfhtqRepository.saveAll(roots);
    }

    @Override

    public List<FHTQXX> getList(String active, Object o, PageRequest request) {
        Page<FHTQXX> all = swhbswfhtqRepository.findAll(request);
        return all.getContent();
    }

    @Override
    @Transactional
    public void processingData(String data, PackageHead heads) {
        try {
            JAXBContext jaxbContext1 = JAXBContext.newInstance(FHTQXXXMLEncodeModel.class);
            Unmarshaller jaxbContextUnmarshaller = jaxbContext1.createUnmarshaller();
            StringReader FHTQXXReader = new StringReader(data);
            FHTQXXXMLEncodeModel swhbswfhtqxmlEncodeModel = (FHTQXXXMLEncodeModel) jaxbContextUnmarshaller.unmarshal(FHTQXXReader);
            List<FHTQXX> roots = swhbswfhtqxmlEncodeModel.getRoots();
            swhbswfhtqRepository.saveAll(roots);

            // 接受税务数据日志  实时的包
            TaxLog taxLog = taxLogService.handlerData(heads);
            roots.forEach(fhtqxx -> {
                TaxDataLog taxDataLog = new TaxDataLog();
                taxDataLog.setDataId(fhtqxx.getId());
                taxDataLog.setLogId(taxLog.getId());
                taxDataLog.setCreateAt(LocalDateTime.now());
                //汇总的单条
                taxDataLogService.save(taxDataLog);
            });


            log.info("处理{}结束", data);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理{}失败", data);
        }

    }
}
